package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hankcs.hanlp.utility.SentencesUtil;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Transactional
@Slf4j
@Async
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    private final WmNewsMapper wmNewsMapper;


    /**
     * 自动扫描文章
     *
     * @param id
     */
    @Override
    public void autoScanWmNews(Integer id) {

//        int a = 1 / 0;

        //1.根据id 查询文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            throw new RuntimeException("文章不存在");
        }

        //2.审核
        if (wmNews.getStatus() == WmNews.Status.SUBMIT.getCode()) {
            //提取纯文本内容和图片
            Map<String, Object> textAndImage = handleTextAndImage(wmNews);

            //自管理的敏感词过滤
            boolean sensitiveScan = handleSensitiveScan((String) textAndImage.get("content"), wmNews);
            if (!sensitiveScan) return;

            //审核内容
            boolean textScan = handleTextScan((String) textAndImage.get("content"), wmNews);
            if (!textScan) return;
            //审核图片
            boolean imageScan = handleImageScan((List<String>) textAndImage.get("images"), wmNews);
            if (!imageScan) return;
        }

        //审核成功，保存app端的相关的文章数据
        ResponseResult responseResult = saveAppArticle(wmNews);
        log.error(String.valueOf(responseResult));
        if (!responseResult.getCode().equals(200)) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
        }
        //回填article_id
        wmNews.setArticleId((Long) responseResult.getData());
        updateWmNews(wmNews, (short) 9, "审核成功");

    }

    private final WmSensitiveMapper wmSensitiveMapper;

    /**
     * 自管理的敏感词审核
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        //获取所有敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> collect = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(collect);
        //查看文章是否包含
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0) {
            updateWmNews(wmNews, 2, "文章包含敏感词" + map);
            return false;
        }
        return true;
    }

    private final IArticleClient articleClient;

    private final WmChannelMapper wmChannelMapper;
    private final WmUserMapper wmUserMapper;

    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        //布局
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }
        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }
//        articleClient.saveArticle(dto);


        //设置文章id todo
        if (wmNews.getArticleId() != null) {
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        ResponseResult responseResult = articleClient.saveArticle(dto);
        return responseResult;
    }

    private final GreenImageScan greenImageScan;
    private final FileStorageService fileStorageService;

    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        if (images == null || images.isEmpty()) return true;
        boolean flag = true;
        images = images.stream().distinct().collect(Collectors.toList());
        ArrayList<byte[]> imageBytes = new ArrayList<>();
        //下载图片
        images.forEach(image -> imageBytes.add(fileStorageService.downLoadFile(image)));
        try {
            Map map = greenImageScan.imageScan(imageBytes);
            if (map != null) {
                if (map.get("suggestion").equals("block")) {
                    flag = false;
                    updateWmNews(wmNews, 2, "图片审核失败");
                }
                if (map.get("suggestion").equals("review")) {
                    flag = false;
                    updateWmNews(wmNews, 3, "图片中存在不确定内容");
                }
            }
        } catch (Exception e) {
            flag = false;
            throw new RuntimeException(e);
        }
        log.info("审核通过");
        return flag;
    }

    private final GreenTextScan greenTextScan;

    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        if (content.length() == 0) return true;
        try {
            Map map = greenTextScan.greeTextScan(content);
            if (map != null) {
                if (map.get("suggestion").equals("block")) {
                    flag = false;
                    updateWmNews(wmNews, 2, "审核失败");
                }
                if (map.get("suggestion").equals("review")) {
                    flag = false;
                    updateWmNews(wmNews, 3, "文章中存在不确定内容");
                }
            }
        } catch (Exception e) {
            flag = false;
            throw new RuntimeException(e);
        }
        log.info("审核通过");
        return flag;
    }

    /**
     * 修改文章内容
     *
     * @param wmNews
     * @param x
     * @param str
     */
    private void updateWmNews(WmNews wmNews, int x, String str) {
        wmNews.setStatus((short) x);
        wmNews.setReason(str);
        wmNewsMapper.updateById(wmNews);
    }

    private Map<String, Object> handleTextAndImage(WmNews wmNews) {
        StringBuilder content = new StringBuilder();
        if (StringUtils.isNotBlank(wmNews.getTitle())) {
            content.append(wmNews.getTitle());
        }
        ArrayList<String> images = new ArrayList<>();
        if (StringUtils.isNotBlank(wmNews.getContent())) {
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            maps.forEach(
                    map -> {
                        if ("text".equals(map.get("type"))) {
                            //内容
                            content.append(map.get("value"));
                        } else if ("image".equals(map.get("type"))) {
                            //图片
                            images.add((String) map.get("value"));
                        }
                    }
            );

        }
        //封面
        if (wmNews.getImages() != null) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("content", content.toString());
        hashMap.put("images", images);
        return hashMap;
    }
}
